// pages/home/home.js
const API = require('../../utils/api.js'); // 引入封装好的 API 方法
const { get } = require('../../utils/request.js');

//https://www.mxnzp.com 注册申请

Page({
  data: {
    // 餐厅数据
    restaurants: [],
    // 当前推荐餐厅
    recommendedRestaurants: [],
    // 是否暗黑模式
    isDarkMode: false,
    // 摇一摇状态
    isShaking: false,
    // 是否显示手动刷新按钮（当传感器不可用时）
    showManualRefresh: false
  },

   async onLoad() {
     //获取经纬度
    const { latitude, longitude } = await API.getFuzzyLocation()
    //获取数据来源
    const sourceList = await this.getNearbyRestaurants(latitude,longitude)
    this.setData({
      restaurants:sourceList
    })
    this.checkDarkMode();
    this.getRandomRestaurants();
    this.startShakeListener();
  },

  onUnload() {
    this.stopShakeListener();
  },

  // 检查系统暗黑模式
  checkDarkMode() {
    const systemInfo = wx.getSystemInfoSync();
    this.setData({
      isDarkMode: systemInfo.theme === 'dark'
    });
  },

  // 切换暗黑模式
  toggleDarkMode() {
    const newMode = !this.data.isDarkMode;
    this.setData({
      isDarkMode: newMode
    });
    wx.showToast({
      title: newMode ? '暗黑模式已开启' : '浅色模式已开启',
      icon: 'success'
    });
    
    // 保存到本地存储
    wx.setStorageSync('isDarkMode', newMode);
    
    // 设置全局样式
    if (newMode) {
      wx.setBackgroundColor({
        backgroundColor: '#1a1a1a'
      });
    } else {
      wx.setBackgroundColor({
        backgroundColor: '#f5f5f5'
      });
    }
  },

  // 跳转到自己做页面
  goToDIY() {
    wx.navigateTo({
      url: '/pages/diy/diy'
    });
  },



  // 随机推荐餐厅
  getRandomRestaurants() {
    const shuffled = [...this.data.restaurants].sort(() => 0.5 - Math.random());
    const recommended = shuffled.slice(0, 3);
    this.setData({
      recommendedRestaurants: recommended
    });
  },

  // 收藏/取消收藏
  toggleCollect(e) {
    const id = e.currentTarget.dataset.id;
    const restaurants = this.data.restaurants.map(item => 
      item.id === id ? { ...item, isCollected: !item.isCollected } : item
    );
    const recommended = this.data.recommendedRestaurants.map(item => 
      item.id === id ? { ...item, isCollected: !item.isCollected } : item
    );
    this.setData({
      restaurants,
      recommendedRestaurants: recommended
    });
    // 更新本地存储
    const favorites = recommended.filter(item => item.isCollected);
    wx.setStorageSync('favoriteRestaurants', favorites);
    wx.showToast({
      title: recommended.find(item => item.id === id).isCollected ? '收藏成功' : '取消收藏',
      icon: 'success'
    });
  },
  // 分享餐厅
  shareRestaurant(e) {
    const restaurant = e.currentTarget.dataset.item;
    wx.showShareMenu({
      withShareTicket: true
    });
  },
  // 启动摇一摇监听
  startShakeListener() {
    // 摇一摇检测参数
    this.shakeData = {
      lastX: 0,
      lastY: 0,
      lastZ: 0,
      lastTime: 0,
      shakeCount: 0,
      lastShakeTime: 0,
      isListening: false
    };
    
    // 先停止之前的监听
    this.stopShakeListener();
    
    wx.startAccelerometer({
      interval: 'ui',
      success: () => {
        this.shakeData.isListening = true;
        this.shakeListener = wx.onAccelerometerChange((res) => {
          const current = {
            x: res.x,
            y: res.y,
            z: res.z,
            time: Date.now()
          };
          
          // 防抖：2000ms内不重复触发
          if (current.time - this.shakeData.lastShakeTime < 2000 || this.data.isShaking) {
            return;
          }
          
          // 计算加速度变化幅度（简化计算，提高性能）
          const deltaX = Math.abs(current.x - this.shakeData.lastX);
          const deltaY = Math.abs(current.y - this.shakeData.lastY);
          const deltaZ = Math.abs(current.z - this.shakeData.lastZ);
          
          // 总变化量
          const totalDelta = deltaX + deltaY + deltaZ;
          
          // 提高阈值，避免轻微晃动
          const threshold = 2.2;
          
          if (totalDelta > threshold) {
            this.shakeData.lastShakeTime = current.time;
            this.handleShake();
          }
          
          // 更新上一次数据
          this.shakeData.lastX = current.x;
          this.shakeData.lastY = current.y;
          this.shakeData.lastZ = current.z;
        });
      },
      fail: (err) => {
        console.log('启动加速度传感器失败:', err);
        this.setData({ showManualRefresh: true });
      }
    });
  },
  // 停止摇一摇监听
  stopShakeListener() {
    if (this.shakeData && this.shakeData.isListening) {
      try {
        wx.stopAccelerometer();
        this.shakeData.isListening = false;
      } catch (error) {
        console.log('停止加速度传感器失败:', error);
      }
    }
    // 清理监听器引用
    this.shakeListener = null;
  },

  // 处理摇一摇事件
  async handleShake() {
    if (this.data.isShaking) return;
    
    this.setData({ isShaking: true });
    
    try {
      // 震动反馈 - 长震动模式
      wx.vibrateLong();
    } catch (vibrateError) {
      console.log('震动失败:', vibrateError);
    }
    
    // 强制重新获取数据
    try {
      const { latitude, longitude } = await API.getFuzzyLocation();
      const sourceList = await this.getNearbyRestaurants(latitude, longitude);
      this.setData({
        restaurants: sourceList
      });
    } catch (error) {
      console.log('重新获取数据失败:', error);
    }
    
    // 重新随机推荐餐厅
    this.getRandomRestaurants();
    
    // 添加成功提示
    wx.showToast({
      title: '摇一摇成功！',
      icon: 'success',
      duration: 1200
    });
    
    // 重置摇一摇状态
    this.shakeData.shakeCount = 0;
    this.shakeData.lastShakeTime = Date.now();
    
    setTimeout(() => {
      this.setData({ isShaking: false });
    }, 1200);
  },
  // 跳转到收藏页面
  goToFavorites() {
    wx.navigateTo({
      url: '/pages/favorites/favorites'
    });
  },
  // 数据分享
  onShareAppMessage(e) {
    const item = e.target.dataset.item;
    return {
      title: `推荐餐厅：${item.name}`,
      path: '/pages/home/home',
      imageUrl: item.photos?.[0]?.url || '/images/empty-icon.png'
    };
  },

  // 图片加载失败处理
  onImageError(e) {
    const id = e.currentTarget.dataset.id;
    const restaurants = this.data.recommendedRestaurants;
    const index = restaurants.findIndex(item => item.id === id);
    
    if (index !== -1) {
      // 设置默认图片
      restaurants[index].photos = [{ url: '/images/empty-icon.png' }];
      this.setData({
        recommendedRestaurants: restaurants
      });
    }
  },

  // 调高德 Web 服务
  async getNearbyRestaurants (latitude, longitude) {
    const {data} = await API.thirdRequest({
       url : 'https://restapi.amap.com/v3/place/around',
       data:{
        key : '47eaeb425a1f9340c1714ec937481782',
        location:`${longitude},${latitude}`,
        keywords:'餐厅',
        radius:5000,
        offset:200,
        page:1
       }
    })
    return data.pois;
  }
})